//
//  STSegmentView.swift
//  Story
//
//  Created by 汤泽川 on 2019/4/12.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import UIKit
import SnapKit

protocol STSegmentViewDelegate : NSObjectProtocol {
    func didSelectIndex(currentIndex : Int) -> Void
}

class STSegmentView: UIView {
    
    public weak var delegate : STSegmentViewDelegate?
    
    private(set) var currentIndex : Int = 0
    private let scrollView = UIScrollView()
    
    private let selectColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
    private let unselectColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
    
    private var items : [String]?
    private var itemBtns = [UIButton]()
    
    convenience init(items : [String]) {
        self.init(frame: CGRect.zero)
        self.items = items
        setupItems()
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRect.zero)
        self.addSubview(scrollView)
        self.scrollView.alwaysBounceVertical = false
        self.scrollView.showsHorizontalScrollIndicator = false
        self.scrollView.showsVerticalScrollIndicator = false
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func updateConstraints() {
        super.updateConstraints()
        self.scrollView.snp.updateConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    public func updateSegment(items : [String]) {
        self.items = items
        setupItems()
        currentIndex = NSNotFound
        self.scrollView.contentOffset = CGPoint.zero
    }
    
    private func setupItems() {
        for btn in itemBtns {
            btn.removeFromSuperview()
        }
        itemBtns.removeAll()

        guard let items = self.items else {
            return
        }
        
        itemBtns = items.map { title in
            let btn = UIButton()
            btn.setTitle(title, for: .normal)
            btn.setTitleColor(unselectColor, for: .normal)
            return btn
        }
        var currentBtn : UIView = self.scrollView
        for (index,btn) in itemBtns.enumerated() {
            self.scrollView.addSubview(btn)
            btn.snp.updateConstraints { (make) in
                if index == 0 {
                    make.left.equalTo(currentBtn).offset(8)
                } else {
                    make.left.equalTo(currentBtn.snp_right).offset(8)
                }
                make.top.equalToSuperview()
                make.height.equalToSuperview()
                if index == itemBtns.count - 1 {
                    make.right.equalToSuperview().offset(-8)
                }
            }
            currentBtn = btn;
            btn.tag = index
            btn.addTarget(self, action: #selector(didClickSegmentBtn(sender:)), for: .touchUpInside)
        }
    }
    
    public func updateSelectItem(index : Int) {
        if index == currentIndex {
            return
        }
        var lastIndex = currentIndex
        if currentIndex == NSNotFound {
            lastIndex = index
        }
        var index = index
        index = max(0, index)
        index = min(index, itemBtns.count - 1)
        currentIndex = index
        let lastBtn = itemBtns[lastIndex]
        let currentBtn = itemBtns[currentIndex]
        lastBtn.setTitleColor(unselectColor, for: .normal)
        currentBtn.setTitleColor(selectColor, for: .normal)
        if currentBtn.leading < self.scrollView.contentOffset.x {
            UIView.animate(withDuration: 0.1) {
                self.scrollView.contentOffset.x = currentBtn.leading - 8
            }
        } else if currentBtn.trailing > self.scrollView.contentOffset.x + self.width {
            UIView.animate(withDuration: 0.1) {
                self.scrollView.contentOffset.x = currentBtn.trailing - self.width + 8
            }
        }
        UIView.animate(withDuration: 0.2) {
            lastBtn.transform = CGAffineTransform.identity
            currentBtn.transform = CGAffineTransform.init(scaleX: 1.2, y: 1.2)
        }
        self.delegate?.didSelectIndex(currentIndex: currentIndex)
    }
    
    @objc private func didClickSegmentBtn(sender : UIButton) {
        updateSelectItem(index: sender.tag)
    }
    
}
